//
//  ProgressImageView.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/20.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit

class ProgressImageView: UIImageView {

    //外部传递的参数
    var progress: CGFloat = 0 {
    
        didSet{
            progressView.progress = progress
            
        }
    
    }
    
    init() {
    
        super.init(frame: CGRectZero)
    
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    //设置UI界面
    private func setUpUI() {
    
        //添加控件
        addSubview(progressView)
        
        progressView.backgroundColor = UIColor.clearColor()
        
        //设置自动布局
        progressView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.snp_edges)
            
        }
    
    }

    //懒加载控件
    private lazy var progressView: ProgressView = ProgressView()

}

/// 进度视图
private class ProgressView: UIView {

    var progress: CGFloat = 0 {
        
        didSet{
            
            //进行重绘
            setNeedsDisplay()
            
        }
        
    }
    
    
    override func drawRect(rect: CGRect) {
        
        //进行绘画
        
        let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
        
        let r = min(rect.width * 0.5, rect.height * 0.5)
        
        let start = CGFloat(-M_PI_2)
        
        let end = start + progress * 2 * CGFloat(M_PI)
        
        let path = UIBezierPath(arcCenter: center, radius: r, startAngle: start, endAngle: end, clockwise: true)
        
        //设置中心点连接
        path.addLineToPoint(center)
        
        //关闭连线
        path.closePath()
        
        //设置颜色
        UIColor(white: 1.0, alpha: 0.3).setFill()
        
        path.fill()
        
    }

}